<script setup lang="ts">
import {reactive, ref, watch, computed, watchEffect, provide, onMounted, onBeforeMount} from "vue";
import {findAllBySearchContains, findSongsByStyle, randomGenerateSongsByNum} from "@/Network/songApi";
import {
  addUserLove,
  addUserSong,
  deleteUserLove,
  findAllUserSongsByUserOrderByUpdateTimeDesc,
  findUserById
} from "@/Network/userApi";
import type {res, typeSong} from "@/store/dataType";
import {
  clickedPage, currentSearchSongs,
  currentSong,
  currentSongState, itemRecSongs,
  randomSongState,
  songListNum, songSearch,
  songState,
  useRandomCount
} from "@/store/songStore";
import {getHotListenCountSongs, getItemRecSongs} from "@/utils/songUtil";


let songList = ref([])
let loveSongList = ref([])
let currentUserId = localStorage.getItem("userId")

const emit = defineEmits(['love-song-num'])

type Props = {
  pageName: {
    type:string,
    default:' '
  },
  styleName:{
    type:string,
    default:' '
  },
  recName:{
    type:string,
    default:' '
  },
  searchWord:{
    type:string,
    default:' '
  },
}
let propApi = defineProps<Props>()
console.log(propApi.pageName+"的songList组件")
// onMounted(()=>{
//   getLoveSongList()
//   // getOneRandomSong()
// })

onBeforeMount(()=>{
  getLoveSongList()
})
function getLoveSongList() {

  findUserById(currentUserId).then(res=>{
    for(let i = 0;i<res.data.userLoves.length;i++){
      loveSongList.value[i]=res.data.userLoves[i].song
    }
    getSongList()
  })
}

async function getSongList() {
  if(propApi.pageName == "StyleSongListPage"){
    let style = {
      style:propApi.styleName
    }
    let resFindSongsByStyle:res = await findSongsByStyle(style)
    songList.value = resFindSongsByStyle.data
    for(let i = 0;i<songList.value.length;i++){
      songList.value[i].isClicked=isLiked(songList.value[i].id)
    }
  }
  else if(propApi.pageName == "RecommendPage"){
    if(useRandomCount.value<1){
      let resRandomGenerateSongsByNum:res = await randomGenerateSongsByNum(songListNum)
      songList.value = resRandomGenerateSongsByNum.data
      randomSongState.value.songList = resRandomGenerateSongsByNum.data
      useRandomCount.value = useRandomCount.value+1
    }else{
      songList.value = randomSongState.value.songList
    }
    for(let i = 0;i<songList.value.length;i++){
      songList.value[i].isClicked=isLiked(songList.value[i].id)
    }
  }
  else if(propApi.pageName == "HistoryPage"){
    let resfindAllUserSongsByUserOrderByUpdateTimeDesc:res = await findAllUserSongsByUserOrderByUpdateTimeDesc(currentUserId)
    for(let i = 0; i<resfindAllUserSongsByUserOrderByUpdateTimeDesc.data.length;i++){
      songList.value[i]=resfindAllUserSongsByUserOrderByUpdateTimeDesc.data[i].song
      songList.value[i].isClicked=isLiked(songList.value[i].id)
    }
  }
  else if(propApi.pageName == "MyLovePage" || propApi.pageName == "UserPage"){

    let resFindUserById:res = await findUserById(currentUserId)
    for(let i = 0; i<resFindUserById.data.userLoves.length;i++){
      songList.value[i]=resFindUserById.data.userLoves[i].song
      songList.value[i].isClicked=isLiked(songList.value[i].id)
    }
    emit('love-song-num',songList.value.length)
  }
  else if(propApi.pageName == "ItemRecPage"){
    songList.value = await getItemRecSongs(localStorage.getItem("userId"))
    if(songList.value.length==0){
      songList.value = await getHotListenCountSongs()
    }
  }
  else if(propApi.pageName == "HotListenCountRecPage"){
    songList.value = await getHotListenCountSongs()
  }
  else if(propApi.pageName == "SearchPage"){
    // console.log(JSON.stringify(currentSearchSongs.value[0]))
    // console.log("↑")
    //避免 出现 songList.value = {}的情况
    if(JSON.stringify(currentSearchSongs.value[0]) == JSON.stringify({})){
      songList.value = []
    }else{
      songList.value = currentSearchSongs.value
    }

  }
  else {
    if(useRandomCount.value<1){
      let resRandomGenerateSongsByNum:res = await randomGenerateSongsByNum(songListNum)
      songList.value = resRandomGenerateSongsByNum.data
      randomSongState.value.songList = resRandomGenerateSongsByNum.data
      useRandomCount.value = useRandomCount.value+1
    }else{
      songList.value = randomSongState.value.songList
    }
    for(let i = 0;i<songList.value.length;i++){
      songList.value[i].isClicked=isLiked(songList.value[i].id)
    }
  }
}

const isLiked = (songId: string) => {
  //在loveSongList中是否存在id为当前songId的歌曲，如果有的话，就说明该歌是用户喜欢的歌曲。
  return loveSongList.value.some((item) => item.id === songId);
}

function changeToDisliked(songId: string,index){

  deleteUserLove(currentUserId,songId).then(res=>{
    console.log(res.data)
  })
  songList.value[index].isClicked = false
  if(propApi.pageName == "MyLovePage"){
    songList.value.splice(index,1)
    emit('love-song-num',songList.value.length)
  }
}
async function changeToliked(songId: string,index){
  let resAddUserLove:res = await addUserLove(currentUserId,songId)
  console.log("被喜欢的歌曲名为："+resAddUserLove.data.song.title)
  songList.value[index].isClicked = true
}
async function clickSong(songId,index){
  clickedPage.value = propApi.pageName
  console.log("***"+clickedPage.value)
  currentSongState.value.songList = songList.value
  currentSongState.value.currentIndex = index

  let userSongTemp = {
    userId:currentUserId,
    songId:songId
  }
  let resAddUserSong:res = await addUserSong(userSongTemp)
  console.log("被播放的歌曲名为："+resAddUserSong.data.song.title)
  localStorage.setItem("currentSongId",resAddUserSong.data.song.id)


  //貌似会出现index不对应的情况，所以直接找。（现在应该不会了，最开始是因为 随机选歌 那个逻辑没做好。到时随机歌曲不稳定。
  // for(let i =0;i<songList.value.length;i++){
  //   if(currentSongState.value.songList[i].id == songId){
  //     currentSongState.value.currentIndex = i
  //     break
  //   }
  // }
}
</script>

<template>
  <!-- 这里是推荐页面的心动曲目下面的歌曲列表 -->

  <ul class=" flex flex-col gap-2 w-full pb-20">
<!--    <li v-for="(song,index) in songList" @click="playSongFunction(song, songList,index)"-->
    <li v-for="(song,index) in songList"
        class="h-30 flex justify-between items-center hover:bg-[#a5f3fc] rounded-2xl px-2"
        @click="clickSong(song.id,index)"
    >

      <div class="song-and-info flex gap-5 justify-center items-center">
        <img :src=song.imageUrl class="w-25 rounded-xl border-pink-2 border-5">
        <div class="text-cyan-6 font-600 w-50 h-25 whitespace-normal flex items-center justify-start ">{{ song.title }}</div>
      </div>
      <p class="text-gray-6  w-50 h-25 whitespace-normal flex items-center justify-start">{{ song.artist }}</p>
      <div v-if="song.isClicked" class="w-30">
        <img src="../img/love.png " @click="changeToDisliked(song.id, index)" alt="喜欢" class="w-25 hover:w-28">
      </div>
      <div v-else class="w-30">
        <img src="../img/no-love.png " @click="changeToliked(song.id,index)" alt="不喜欢" class="w-25 hover:w-28 ">
      </div>

    </li>
  </ul>


</template>

<style scoped>
div::-webkit-scrollbar {
  display: none;
}
</style>